'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Send, MessageCircle, Eye, Loader2 } from 'lucide-react';
import { ChatMessage, AskRequest } from '@/types';
import { apiClient } from '@/lib/apiClient';

interface ChatWidgetProps {
  chatflowId: string;
  userId?: string;
  onTraceGenerated?: (sessionId: string) => void;
}

export default function ChatWidget({ 
  chatflowId, 
  userId, 
  onTraceGenerated 
}: ChatWidgetProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [sessionId, setSessionId] = useState<string>('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || isLoading) return;

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content: input.trim(),
      timestamp: new Date().toISOString(),
      sessionId,
    };

    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsLoading(true);

    try {
      const request: AskRequest = {
        chatflowId,
        question: input.trim(),
        userId,
        sessionId: sessionId || undefined,
        overrideConfig: {
          analytics: userId ? { langFuse: { userId } } : undefined,
        },
      };

      const response = await apiClient.ask(request);
      
      const assistantMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: response.answer,
        timestamp: new Date().toISOString(),
        sessionId: response.sessionId,
        traceId: response.sessionId,
      };

      setMessages(prev => [...prev, assistantMessage]);
      setSessionId(response.sessionId);
      
      // 通知父组件有新的 trace 生成
      if (onTraceGenerated) {
        onTraceGenerated(response.sessionId);
      }

    } catch (error) {
      console.error('发送消息失败:', error);
      console.error('错误详情:', {
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        request: {
          chatflowId,
          question: input.trim(),
          userId,
          sessionId
        }
      });
      
      const errorMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `抱歉，发送消息时出现错误：${error instanceof Error ? error.message : '未知错误'}。请检查网络连接或稍后重试。`,
        timestamp: new Date().toISOString(),
        sessionId,
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleViewTrace = (traceId: string) => {
    if (traceId) {
      window.open(`/admin/trace/${traceId}`, '_blank');
    }
  };

  return (
    <div className="flex flex-col h-full bg-white rounded-lg shadow-lg">
      {/* 聊天头部 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200">
        <div className="flex items-center space-x-2">
          <MessageCircle className="w-6 h-6 text-primary-600" />
          <h2 className="text-lg font-semibold text-gray-800">AI 助手</h2>
        </div>
        {sessionId && (
          <div className="text-sm text-gray-500">
            会话 ID: {sessionId.slice(-8)}
          </div>
        )}
      </div>

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.length === 0 && (
          <div className="text-center text-gray-500 py-8">
            <MessageCircle className="w-12 h-12 mx-auto mb-4 text-gray-300" />
            <p>开始与 AI 助手对话吧！</p>
          </div>
        )}
        
        {messages.map((message) => (
          <div
            key={message.id}
            className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                message.role === 'user'
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-100 text-gray-800'
              }`}
            >
              <p className="text-sm whitespace-pre-wrap">{message.content}</p>
              <div className="flex items-center justify-between mt-2">
                <span className="text-xs opacity-70">
                  {new Date(message.timestamp).toLocaleTimeString()}
                </span>
                {message.role === 'assistant' && message.traceId && (
                  <button
                    onClick={() => handleViewTrace(message.traceId!)}
                    className="flex items-center space-x-1 text-xs opacity-70 hover:opacity-100 transition-opacity"
                  >
                    <Eye className="w-3 h-3" />
                    <span>查看思考过程</span>
                  </button>
                )}
              </div>
            </div>
          </div>
        ))}
        
        {isLoading && (
          <div className="flex justify-start">
            <div className="bg-gray-100 text-gray-800 px-4 py-2 rounded-lg">
              <div className="flex items-center space-x-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                <span className="text-sm">AI 正在思考中...</span>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </div>

      {/* 输入框 */}
      <form onSubmit={handleSubmit} className="p-4 border-t border-gray-200">
        <div className="flex space-x-2">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="输入您的问题..."
            className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent text-gray-900 placeholder-gray-500"
            disabled={isLoading}
          />
          <button
            type="submit"
            disabled={!input.trim() || isLoading}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <Send className="w-4 h-4" />
          </button>
        </div>
      </form>
    </div>
  );
}
